<?php
declare (strict_types = 1);

namespace App\Models;

/**
 * 会员表
 */
class UserModel extends BaseModel
{
    use SoftDeletes;
    protected $table = 'user';
    const UPDATED_AT = null;

    /**
     * 数据表主键
     * @var string
     */
    protected $primaryKey = 'uid';

    /**
     * 生成邀请码
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getInviteCode()
    {
        $code = rand_code(6);
        $count = self::where("invite_code", $code)->count();
        if ($count == 0) {
            return strtoupper($code);
        }
        return self::getInviteCode();
    }

    /**
     * 余额/积分操作
     * @return void
     */
    public static function edit_balance()
    {
        try {
            $param = request()->input();
            $user = self::find($param['uid']);
            if(!$user) return self::result('',500,'系统繁忙，请重试');
            //余额
            $user_balance = (float)$param['user_balance'];
            $integral = (float)$param['integral'];
            if($param['is_balance'] && $user_balance){
                if($param['is_balance'] == 2){  //扣除
                    if($user['user_balance'] - $user_balance < 0){
                        return self::result('',500,'扣除失败：余额不足');
                    }
                }
                $type = $param['is_balance'] == 1 ? "system_add" : "system_sub";
                $title = UserBillModel::getBillType($type);
                $arr[] = [
                    'uid' => $user['uid'],
                    'link_id' => 1,
                    'pm' => $param['is_balance'] == 1 ? 1 : 0,
                    'title' => $title."余额",
                    'category' => "balance",
                    'type' => $type,
                    'number' => $user_balance,
                    'balance' => $user['user_balance'],
                    'mark' => $title." ".$user_balance.'元余额',
                    'status' => 1,
                    'create_time' => time(),
                ];
            }

            //积分
            if($param['is_integral'] && $integral){
                if($param['is_integral'] == 2){  //扣除
                    if($user['integral'] - $integral < 0){
                        return self::result('',500,'扣除失败：积分不足');
                    }
                }

                $type = $param['is_integral'] == 1 ? "system_add" : "system_sub";
                $title = UserBillModel::getBillType($type);
                $arr[] = [
                    'uid' => $user['uid'],
                    'link_id' => 1,
                    'pm' => $param['is_integral'] == 1 ? 1 : 0,
                    'title' => $title."积分",
                    'category' => "integral",
                    'type' => $type,
                    'number' => $integral,
                    'balance' => $user['integral'],
                    'mark' => $title." ".$integral.' 积分',
                    'status' => 1,
                    'create_time' => time(),
                ];
            }
            if(!$arr) return self::result('',500,'请选择操作项');
            return self::result($arr);
        } catch (\Exception $e) {
            return self::result('',500,$e->getMessage());
        }
    }

    /**
     * 用户列表
     */
    public static function getUserList($pageSize, $page, $map)
    {
        return self::select('*')->where($map)
            ->orderBy('last_time','desc')
            ->paginate($pageSize,[],'page', $page)->toArray();
    }

    /**
     * 后台添加编辑用户
     */
    public static function editUser($data)
    {
        try{
            $uid = $data['uid'];
            unset($data['uid']);
            if(empty($uid)) {
                $check = self::where("mobile", $data['mobile'])->count();
                if($check != 0) {
                    return self::result("",500, "手机号已存在，请更换");
                }
                $data['account'] = $data['mobile'];
                $data['nickname'] = $data['real_name'];
                $data['user_sn'] = uniqid();
                $data['create_time'] = time();
                $data['last_time'] = time();
                $data['create_ip'] = request()->ip();
                $data['user_type'] = "系统创建";
                $data['login_type'] = "系统";
                $data['invite_code'] = self::getInviteCode();
                $res = self::create($data);
                if($res->uid) {
                    return self::result("", 200, "创建成功");
                }
                return self::result("", 500, "创建失败");
            }else {
                $check = self::select(['uid','mobile'])->where("uid", $uid)->first();
                if($data['mobile'] != $check['mobile']) {
                    $check = self::where("mobile", $data['mobile'])->count();
                    if($check != 0) {
                        return self::result("", 500, "手机号已存在，请更换");
                    }
                }
                $res = self::where('uid',$uid)->update($data);
                if($res) {
                    return self::result("", 200, "操作成功");
                }
                return self::result("", 500, "操作失败");
            }

        }catch (\Exception $e){
            return self::result('',500,$e->getMessage());
        }
    }
}
